package com.lishe.lishe.lishe.module.mall.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.auth.activity.AuthActivity;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.SkuObject;
import com.lishe.lishe.lishe.module.mall.fragment.GoodsDetailFragent;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.me.activity.AddAddrActivity;
import com.lishe.lishe.lishe.bean.AddressItem;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShopCarActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.widget.GoodsProDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by lwa on 2017/9/20.
 * & Bin
 * 商品详情，及单品的总页（底部弹窗的实现页面）
 */

public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener {
    private Button callBack;
    private String itemId;
    private Button add;
    private List<SkuObject> skus = new ArrayList<>();
    private List<AddressItem> mAddressList = new ArrayList<>();
    private View mGoodsCar;
    private TextView mGoodsCount;

    private String mAreaId;
    private String mAddrId;
    private String skuId;
    private int count;
    private MallGoods mallGoods;
    private GoodsProDialog mGoodsProDialog;
    private GoodsDetailFragent mGoodsFragment;
    private TextView mGoodsTitle;
    private TextView mDetailTitle;
    private View mSelectGoods;
    private View mSelectDetail;
    private View mBottomLayout;

    public static void jump(Activity activity, String itemId) {
        Intent intent = new Intent(activity, GoodsDetailActivity.class);
        intent.putExtra("itemId", itemId);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemId = getIntent().getStringExtra("itemId");
        setContentView(R.layout.activity_mall_goods);
        initView();
        initListener();
        getAddress();
        regisBrocastReciver();
    }

    private void initView() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mGoodsFragment = GoodsDetailFragent.newInstance(itemId);
        transaction.replace(R.id.content, mGoodsFragment);
        transaction.commit();

        mBottomLayout = findViewById(R.id.bottom_layout);
        callBack = findViewById(R.id.callBack);
        add = findViewById(R.id.add);
        mGoodsCar = findViewById(R.id.goods_cart);
        mGoodsCount = findViewById(R.id.goods_count);
        //title
        mGoodsTitle = findViewById(R.id.title_goods);
        mDetailTitle = findViewById(R.id.title_detail);
        mSelectGoods = findViewById(R.id.select_goods);
        mSelectDetail = findViewById(R.id.select_detail);
    }

    private void initListener() {
        callBack.setOnClickListener(this);
        add.setOnClickListener(this);
        mGoodsCar.setOnClickListener(this);
        findViewById(R.id.goods_layout).setOnClickListener(this);
        findViewById(R.id.detail_layout).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.callBack:
                finish();
                break;
            case R.id.add:
                if (TextUtils.isEmpty(Globals.getToken())) {
                    //如果未登录登录，跳到登录界面
                    Intent i = new Intent(this, AuthActivity.class);
                    i.putExtra("from", "GoodsDetail");
                    startActivity(i);
                    return;
                }
                mallGoods = mGoodsFragment.getMallObject();
//                if ("instock".equals(mallGoods.getApprove_status())) {
//                    toast("商品已下架");
//                    return;
//                }
                if(mallGoods==null||mallGoods.getShop_id() == null){
                    return;
                }

                if (mallGoods.getShop_id().equals("32")) {//等于32说明为全球购商品
                    toast(getString(R.string.not_support_global_goods));
                    return;
                }
                showProDialog(mallGoods, GoodsProDialog.FROM_ADDSHOPCAR);
                break;
            case R.id.goods_cart:
                if (LSWebHelper.getInstance().isUserLogined()) {
                    ShopCarActivity.jump(GoodsDetailActivity.this);
                } else {
                    Intent i = new Intent(this, AuthActivity.class);
                    i.putExtra("from", "GoodsDetail");
                    startActivity(i);
                }
                break;
            case R.id.goods_layout:
                mGoodsFragment.scrollTo(1);
                break;
            case R.id.detail_layout:
                mGoodsFragment.scrollTo(0);
                break;
        }
    }

    //重置顶部tab选中与否
    public void resetTitle(int index) {
        if (index == 0) {
            AnimatorSet set = new AnimatorSet();
            ObjectAnimator animatorX = ObjectAnimator.ofFloat(mGoodsTitle, "scaleX", 1, 1.1f);
            ObjectAnimator animatorY = ObjectAnimator.ofFloat(mGoodsTitle, "scaleY", 1, 1.1f);
            ObjectAnimator animatorX1 = ObjectAnimator.ofFloat(mDetailTitle, "scaleX", 1.1f, 1);
            ObjectAnimator animatorY1 = ObjectAnimator.ofFloat(mDetailTitle, "scaleY", 1.1f, 1);
            set.setDuration(200);
            set.playTogether(animatorX, animatorY, animatorX1, animatorY1);
            set.start();
            mGoodsTitle.setTextColor(getResources().getColor(R.color.color_ff4138));
            mSelectGoods.setBackgroundColor(getResources().getColor(R.color.color_ff4138));
            mSelectGoods.setVisibility(View.VISIBLE);
            mDetailTitle.setTextColor(getResources().getColor(R.color.gray_3));
            mSelectDetail.setBackgroundColor(getResources().getColor(R.color.gray_3));
            mSelectDetail.setVisibility(View.GONE);
        } else {
            AnimatorSet set = new AnimatorSet();
            ObjectAnimator animatorX = ObjectAnimator.ofFloat(mDetailTitle, "scaleX", 1, 1.1f);
            ObjectAnimator animatorY = ObjectAnimator.ofFloat(mDetailTitle, "scaleY", 1, 1.1f);
            ObjectAnimator animatorX1 = ObjectAnimator.ofFloat(mGoodsTitle, "scaleX", 1.1f, 1);
            ObjectAnimator animatorY1 = ObjectAnimator.ofFloat(mGoodsTitle, "scaleY", 1.1f, 1);
            set.setDuration(200);
            set.playTogether(animatorX, animatorY, animatorX1, animatorY1);
            set.start();
            mGoodsTitle.setTextColor(getResources().getColor(R.color.gray_3));
            mSelectGoods.setBackgroundColor(getResources().getColor(R.color.gray_3));
            mSelectGoods.setVisibility(View.GONE);
            mDetailTitle.setTextColor(getResources().getColor(R.color.color_ff4138));
            mSelectDetail.setBackgroundColor(getResources().getColor(R.color.color_ff4138));
            mSelectDetail.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置bottom是否展示
     */
    public void showBottom(boolean isShow) {
        if (isShow) {
            mBottomLayout.setVisibility(View.VISIBLE);
        } else {
            mBottomLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 获取收货地址
     */
    private void getAddress() {
        HttpUserCenter.getAddressList(null, response);
    }

    /**
     * 获取收货地址
     */
    private void checkSKU() {
        String msg;
        if (mallGoods == null) {
            mallGoods = mGoodsFragment.getMallObject();
        }
        if (mAreaId == null) {
            msg = "请添加或选择地址";
            toast(msg);
            return;
        }
        if (skuId == null) {
            msg = "选择商品规格！";
            toast(msg);
            return;
        }
        LoadingUtils.createLoadingDialog(this, "正在检测库存...", true);
        HttpMall.checkSKU(Globals.getToken(), mAreaId, skuId, mallGoods.getShop_id(), mallGoods.getItem_id(), checkSkuResponse);
    }

    /**
     * 添加购物车
     */
    private void addShoppingCart() {//注意此处的skuId不一定是mallGoods.getSkuid()
        if (mallGoods == null) {
            mallGoods = mGoodsFragment.getMallObject();
        }
        LoadingUtils.closeDialog();
        Log.e("address--", mAreaId);
        LoadingUtils.createLoadingDialog(this, "正在添加到购物车...", true);
        HttpMall.addShoppingCart(Globals.getToken(), mallGoods.getItem_id(), skuId, count + "", mallGoods.getShop_id(), mallGoods.getJd_ids(), mAreaId, addShoppingCartResponse);
    }

    /**
     * 添加到购物车
     */
    AsyncHttpResponseHandler addShoppingCartResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("添加购物车", result);
            try {
                JSONObject json = new JSONObject(result);
                String msg = json.optString("msg");
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    mGoodsProDialog.dismiss();
                    toast(json.optString("data"));
                    getGoodsCount();
                } else {
                    LoadingUtils.closeDialog();
                    toast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
            LoadingUtils.closeDialog();
        }
    };

    /**
     * 检测库存
     */
    AsyncHttpResponseHandler checkSkuResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("检测库存", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    if (dataObject.optInt("status") > 0) {
                        changeDefaultAddr();
                        addShoppingCart();
                    } else {
                        toast(dataObject.optString("message"));
                    }
                } else {
                    LoadingUtils.closeDialog();
                    String msg = json.optString("msg");
                    toast("检测库存，" + msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            toast(getString(R.string.network_or_server_exception));
        }
    };

    // 修改默认地址
    private void changeDefaultAddr() {
        HashMap params = new HashMap();
        LogUtil.e("addrId", "addr_id_____" + mAddrId);
        params.put("addrId", mAddrId);
        HttpUserCenter.changeDefaultAddr(params, new LSWebHelper.WebCallBack() {
            @Override
            public void onSuccess(JSONObject dataJson, String dataString, String message) {}

            @Override
            public void onFailure(String message) {}
        });

    }

    /**
     * 获取地址列表
     */
    LSWebHelper.WebCallBack response = new LSWebHelper.WebCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            String data = dataString;
            LogUtil.i("地址信息", data);
            mAddressList = JSON.parseArray(dataString, AddressItem.class);
            for (int i = 0; i < mAddressList.size(); i++) {
                //默认地址选中
                if (mAddressList.get(i).getDef_addr() == 1) {
                    mAddressList.get(i).setCheck(true);
                }
            }
            //选择地址弹窗正在展示 reset data
            if (mGoodsProDialog != null && mGoodsProDialog.isShowing()) {
                mGoodsProDialog.resetAddressData(mAddressList);
            }
        }

        @Override
        public void onFailure(String message) {
            Toast.makeText(GoodsDetailActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 加入购物车-属性地址数量弹窗
     */
    public void showProDialog(final MallGoods mallGoods, int from) {
        if (mGoodsProDialog != null && mGoodsProDialog.isShowing()) {
            return;
        }

        skus.clear();
        skus.addAll(mGoodsFragment.getSkus());

        if (skus == null || skus.size() == 0) {
            return;
        }

        mGoodsProDialog = new GoodsProDialog(this, from, mGoodsFragment.getGoodStatus());
        mGoodsProDialog.setPrice(mallGoods.getPrice());
        mGoodsProDialog.setImgUrl(mallGoods.getImage_default_id());
        mGoodsProDialog.setAddressList(mAddressList);
        mGoodsProDialog.setSku(skus);
        mGoodsProDialog.setShop_id(mallGoods.getShop_id());
        mGoodsProDialog.setItem_id(mallGoods.getItem_id());
        mGoodsProDialog.setOnItemOnclickListener(new GoodsProDialog.ItemOnclickListener() {
            @Override
            public void onAddressItemOnclickListener(String address0, int position) {
                LogUtil.i("地址", address0);
                mAreaId = mAddressList.get(position).getArea_id();
                mAddrId = mAddressList.get(position).getAddr_id();
            }

            @Override
            public void onSkuItemOnclickListener(boolean isDefalut, String skuId0) {
                if (isDefalut) {
                    skuId = mallGoods.getSku_id();
                } else {
                    skuId = skuId0;
                }
            }

            //确定
            @Override
            public void onComfitOnclickListener(int count0) {
                count = count0;
                checkSKU();
            }

            @Override
            public void onAddAddress() {
                AddAddrActivity.jumpForResult(GoodsDetailActivity.this, Globals.REQUSE_CODE_AddAddrActivity, 1, null);
            }
        });
        mGoodsProDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Globals.REQUSE_CODE_AddAddrActivity) {
                getAddress();
            }
        }
    }

    private void getGoodsCount() {
        HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
    }

    /**
     * 商品数量
     */
    AsyncHttpResponseHandler getGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            LogUtil.i("购物车商品数量", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject data = json.optJSONObject("data");
                    int num = data.optInt("num");
                    if (num > 0) {
                        if (num > 99) {
                            mGoodsCount.setText("99+");
                        } else {
                            mGoodsCount.setText(num + "");
                        }
                        mGoodsCount.setVisibility(View.VISIBLE);
                    } else {
                        mGoodsCount.setVisibility(View.GONE);
                    }
                } else {
                    mGoodsCount.setVisibility(View.GONE);
                    LoadingUtils.closeDialog();
                    JSONObject msgObject = json.optJSONObject("msg");
                    String msgString = StringUtils.unicodeToString("msg", msgObject.toString());
                    Log.e("商品", "" + msgString);
                    if (msgString != null && msgString.contains("请登录")) {
                        toast("还未登录，无法获取购物车信息！");
                    } else {
                        toast("获取购物车信息，" + msgString);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
        }
    };

    //-----------------------------选择地址广播处理-----------------------------
    private void regisBrocastReciver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Globals.ACTION_UPADDRESS);
        registerReceiver(receiver, intentFilter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Globals.ACTION_UPADDRESS)) {
                Log.e("收到广播", "哈哈更新UI");
                getAddress();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (!LSWebHelper.getInstance().isUserLogined()) {
            //mGoodsCar.setVisibility(View.GONE);
        } else {
            //mGoodsCar.setVisibility(View.VISIBLE);
            getGoodsCount();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 底部购物车按钮的改变
     */
    public void resetGoodsStatus(int status) {
        if (status == GoodsDetailFragent.INSTOCK) {//下架
            add.setText("商品已下架");
            add.setBackgroundColor(getResources().getColor(R.color.gray_9));
            add.setEnabled(false);
        }/* else if (status == NOGOODS) {//库存不足
            add.setText("库存不足");
            add.setBackground(getResources().getDrawable(R.drawable.selector_btn_gray));
            add.setEnabled(false);
        } */else if (status == GoodsDetailFragent.ONSALE) {//在售
            add.setText("加入购物车");
            add.setBackgroundColor(getResources().getColor(R.color.color_ff4138));
            add.setEnabled(true);
        }
    }
}
